@echo off
setlocal enabledelayedexpansion

REM Docker MySQL Windows Management Script
REM Usage: docker-mysql-windows.bat [start|stop|status|connect|logs]

set CONTAINER_NAME=property-mysql
set ROOT_PASSWORD=root123
set DB_NAME=property_cleaning
set DB_USER=property_user
set DB_PASSWORD=property_pass
set PORT=3306

REM Check if Docker is running
docker --version >nul 2>&1
if errorlevel 1 (
    echo Error: Docker is not installed or not in PATH
    pause
    exit /b 1
)

docker info >nul 2>&1
if errorlevel 1 (
    echo Error: Docker is not running
    echo Please start Docker Desktop first
    pause
    exit /b 1
)

if "%1"=="start" goto :start
if "%1"=="stop" goto :stop
if "%1"=="status" goto :status
if "%1"=="connect" goto :connect
if "%1"=="logs" goto :logs
if "%1"=="" goto :menu

echo Usage: %0 [start^|stop^|status^|connect^|logs]
goto :eof

:start
echo Starting MySQL in Docker...

REM Stop existing container
docker stop %CONTAINER_NAME% >nul 2>&1
docker rm %CONTAINER_NAME% >nul 2>&1

REM Start new container
docker run -d ^
    --name %CONTAINER_NAME% ^
    -p %PORT%:3306 ^
    -e MYSQL_ROOT_PASSWORD=%ROOT_PASSWORD% ^
    -e MYSQL_DATABASE=%DB_NAME% ^
    -e MYSQL_USER=%DB_USER% ^
    -e MYSQL_PASSWORD=%DB_PASSWORD% ^
    mysql:8.0

echo.
echo Waiting for MySQL to be ready...
timeout /t 10 /nobreak >nul

REM Test connection
docker exec %CONTAINER_NAME% mysql -u%DB_USER% -p%DB_PASSWORD% -e "SELECT 'MySQL is ready!' as status;" %DB_NAME% >nul 2>&1
if errorlevel 1 (
    echo Warning: MySQL might still be starting...
    echo You can check status with: %0 status
) else (
    echo MySQL started successfully!
    echo.
    echo Connection info:
    echo   Container: %CONTAINER_NAME%
    echo   Port: %PORT%
    echo   Database: %DB_NAME%
    echo   User: %DB_USER%
    echo   Password: %DB_PASSWORD%
    echo.
    echo Connect with: mysql -h127.0.0.1 -P%PORT% -u%DB_USER% -p%DB_PASSWORD% %DB_NAME%
)
goto :eof

:stop
echo Stopping MySQL container...
docker stop %CONTAINER_NAME%
echo MySQL stopped
goto :eof

:status
echo Checking MySQL status...
docker ps --filter "name=%CONTAINER_NAME%" --format "table {{.Names}}	{{.Status}}	{{.Ports}}"
if errorlevel 1 (
    echo Container %CONTAINER_NAME% not found
) else (
    echo.
    echo To check logs: %0 logs
)
goto :eof

:connect
echo Connecting to MySQL...
docker exec -it %CONTAINER_NAME% mysql -u%DB_USER% -p%DB_PASSWORD% %DB_NAME%
goto :eof

:logs
echo MySQL container logs:
docker logs --tail 50 %CONTAINER_NAME%
goto :eof

:menu
echo.
echo ========================================
echo   Docker MySQL Manager
echo ========================================
echo.
echo 1. Start MySQL
set /p choice=Enter your choice (1-5) or 'q' to quit: 
if "%choice%"=="1" goto :start
if "%choice%"=="2" goto :stop
if "%choice%"=="3" goto :status
if "%choice%"=="4" goto :connect
if "%choice%"=="5" goto :logs
if "%choice%"=="q" goto :eof
if "%choice%"=="Q" goto :eof

pause